<template>
	<view class="content">
		<!-- 顶部背景区域 -->
		<view class="topView">
			<image class="topbg" :src="staticUrl + '/image/mine/recharge/img_top.png'"></image>
			<!-- <view class="top_title">
				<text class="top_t1">充值中心</text>
				<text class="top_t2">感恩回馈 五折优惠</text>
				<text class="top_t3">老用户续费专享活动 超值权益来袭</text>
			</view>
			<image class="card_top" src="../../../static/image/mine/recharge/img_price.png"></image> -->
		</view>
		<!-- 充值手机号区域 -->
		<view class="rechargeView">
			<view class="recharge_title">
				<text class="recharge_t1">手机号码</text>
				<text class="recharge_t2">请输入要充值的手机号</text>
			</view>
			<view class="phone">
				<input class="inputPhone" type="number" placeholder="请输入手机号" placeholder-class="phonePlaceSytle" v-model="telNum" maxlength="11" />
				<image v-if="telNum" :src="staticUrl + '/image/icon_close.png'" @click="clearInput()"></image>
				</view>
			<view class="payTypeView">
				<text class="payType_title">支付方式</text>
				<view class="payTypeItem">
					<view class="ItemL">
						<image :src="staticUrl + '/image/mine/recharge/wechat_selected.png'" style="width: 50rpx;height: 43rpx;"></image>
						<text style="color: #FF8D38;">微信支付</text>
					</view>
					<image :src="staticUrl + '/image/mine/recharge/icon_selected.png'" style="width: 28rpx;height: 28rpx;margin-right: 78rpx;"></image>
				</view>
				
				<!-- p[ay] -->
				<view class="payView">
					<image class="payNow" :src="staticUrl + '/image/mine/recharge/img_rechargeNow.png'" @click="tocharge()"></image>
					<image class="tips" :src="staticUrl + '/image/mine/recharge/icon_sale.png'"></image>
				</view>
			</view>
		</view>
		<!-- 说明 -->
		<!-- <image src="../../../static/image/mine/recharge/img_0.png" style="width: 710rpx;height: 875rpx;margin-top: 60rpx;margin-bottom: 15rpx;"></image> -->
	</view>
</template>

<script>
import * as api from '@/api/login';
import config from '@/config.js';
export default {
	data() {
		return {
			staticUrl:this.$config.StaticUrl,
			telNum: '',
			payType: 'wxPay', // alipay 、 wx
			eiOrder:{}, //存放订单所需的所有信息
			phoneReg: new RegExp(/^1[3-9]\d{9}$/), //手机号正则验证
			code:'', //微信登录获取的code
		};
	},
	onLoad(option) {
		this.telNum = option.phone;
		this.userId = this.$store.state.userInfo.currentUser.userId;
	},
	methods: {
		clearInput(){
			this.telNum = '';
		},
		tocharge() {
			let that = this;
			that.$utils.throttle(() => {
				if (that.telNum.trim().length <= 0) {
					that.$toast('手机号不能为空',{icon:'error'});
					return;
				} else if (!that.phoneReg.test(that.telNum)) {
					that.$toast('手机号格式错误',{icon:'error'});
					return;
				} 
				console.log('charge>>>>>');
				uni.getProvider({
					service: 'payment',
					success(res) {
						let arrStr = res.provider.join(',');
						if (arrStr.indexOf('alipay') === -1 && arrStr.indexOf('wxpay') === -1) {
							uni.showToast({
								title: '暂不支持支付',
								icon: 'none'
							});
							return;
						};
						// 调用用户充值接口
						that.wxlogin();
					},
					fail(res) {
						console.log('获取支付通道fail>>', res);
					}
				});
			},5000)
		},
		// 登录获取code换取
		wxlogin(){
			let that = this;
			uni.login({
				success(res) {
					console.log('login>',res);
					that.code = res.code;
					that.rechargeUserPurse();
				},fail(err) {
					console.log(err);
				}
			})
		},
		// 用户钱包充值
		rechargeUserPurse(){
			let that = this;
			let userId = this.userId;
			let data = {
				userId: userId,
				action: 'rechargeUserPurse',
				params: {
					subject: '易爱用户充值',
					payType: that.payType,
					amount: '1499',
					mobile:that.telNum
				}
			};
			api.rechargeUserPurse(data).then(function(res) {
					console.log('rechargeUserPurse success', res);
					if(res.data.code === 2000) {
						that.eiOrder = res.data.data.eiOrder;
						// 调用支付
						that.requestPayment();
					}else {
						if(res.data.message == "手机号不存在") {
							that.$toast(res.data.message);
							return;
						}
					}
				}).catch(function(err) {
					console.log('rechargeUserPurse fail', err);
			});
		},
		// 异步 调用支付  先从服务器获取订单信息
		async requestPayment() {
			let that = this;
			let orderInfo;
			// 微信
			orderInfo = await this.getOrderInfo();
			if (orderInfo.code != 2000) {
				console.log('获取订单信息失败', orderInfo);
				uni.showModal({
					content: '获取订单信息失败',
					showCancel: false
				});
				return;
			}
			uni.requestPayment({
				timeStamp:orderInfo.data.orderString.timeStamp.toString(),
				nonceStr:orderInfo.data.orderString.nonceStr,
				package:'prepay_id=' + orderInfo.data.orderString.prepayId,
				signType:"MD5",
				paySign:orderInfo.data.orderString.sign,
				success: (res) => {
					console.log('request success>>-',res);
					var i = 0;
					let T = setInterval(async() =>{
						let payState = await that.requestPayState(that.eiOrder.orderId);
						console.log(payState);
						if(payState.code === 2000 && payState.data.commonOrderInfo.state >= 2) {
							// console.log('调用支付成功>>>', res.rawdata);
							clearInterval(T);
							uni.redirectTo({
								url:'rechargeSuccess/rechargeSuccess'
							});
						}else {
							if(i >= 5){
								uni.showToast({
									title: '付款失败,请重试!',
									icon: 'none'
								});
								clearInterval(T);
							};
							i++;
						}
					},1000);
				},
				fail(res) {
					console.log('fail::', res);
					// #ifdef MP-WEIXIN
					if(res.errMsg == "requestPayment:fail cancel") {
						that.$toast('付款失败',{icon:'error'});
					}
					// #endif
					// #ifndef MP-WEIXIN
					if (res.errCode == -100) {
						that.$toast('付款失败',{icon:'error'});
					}
					// #endif
				}
			});
		},
		// 获取订单信息 alipay
		getOrderInfo() {
			return new Promise(res => {
				let that = this;
				let userId = this.userId;
				let eiOrder = this.eiOrder;
				let data = {
					userId: userId,
					action: that.payType,
					params: {
						code:that.code,
						subject: eiOrder.subject,
						outTradeNo: eiOrder.orderId,
						totalAmount:eiOrder.totalPrice,
						// totalAmount:'0.01',
						body:'五折优惠',
						from:'EI_user_mini'
					}
				};
				console.log('request:::',data);
				api.JSApiPay(data).then(function(result) {
					console.log('appPay success', result);
					if (result.data.code != 2000) {
						that.$toast('获取订单信息失败');
						return;
					} else {
						res(result.data);
					}
				}).catch(function(err) {
					console.log('appPay fail', err);
					res(err);
				});
			});
		},
		// 查询订单状态（从服务器端检查有没有支付成功）
		requestPayState(orderId){
			return new Promise(res => {
				let that = this;
				let userId = this.userId;
				let data = {
					userId: userId,
					action: 'getOrderInfo',
					params: {
						orderId: orderId,
						mobile: ''
					}
				};
				api.getOrderInfo(data).then(function(result) {
					console.log('getOrderInfo success', result);
					if (result.data.code != 2000) {
						uni.showToast({
							title: '获取订单信息失败',
							icon: 'none'
						});
						return;
					} else {
						res(result.data);
					}
				}).catch(function(err) {
					console.log('getOrderInfo fail', err);
					res(err);
				});
			});
		},
		// 监听返回按钮的触发
		onBackPress(options) {
			uni.$emit('updatePurseInfo',{});
			return false;
		},
	}
};
</script>

<style>
page {
	background-color: #fafafa;
}
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.topView {
	width: 750rpx;
	height: 710rpx;
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.topbg {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
}
.top_title {
	top: 78rpx;
	position: absolute;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.top_t1 {
	font-size: 40rpx;
	font-family: Source Han Sans CN;
	font-weight: bold;
	color: #333333;
}
.top_t2 {
	margin-top: 28rpx;
	font-size: 72rpx;
	font-family: Source Han Sans SC;
	font-weight: bold;
	color: #564d70;
}
.top_t3 {
	font-size: 28rpx;
	font-family: Source Han Sans SC;
	font-weight: normal;
	color: #564d70;
}
.card_top {
	width: 690rpx;
	height: 377rpx;
	top: 333rpx;
}
/* ... */
.rechargeView {
	width: 100%;
	margin-top: 48rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.recharge_title {
	width: 100%;
	display: flex;
	align-items: flex-end;
	justify-content: flex-start;
}
.recharge_t1 {
	margin-left: 67rpx;
	font-size: 38rpx;
	font-family: Source Han Sans CN;
	font-weight: bold;
	color: #333333;
}
.recharge_t2 {
	margin-left: 17rpx;
	font-size: 26rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #666666;
}

.phone {
	width: 700rpx;
	height: 115rpx;
	background-color: #f2f2f2;
	border-radius: 50px;
	display: flex;
	align-items: center;
	margin-top: 30rpx;
	position: relative;
}
.phone image {
	position: absolute;
	width: 30rpx;
	height: 30rpx;
	right: 50rpx;
}

.inputPhone {
	margin-left: 45rpx;
	width: 600rpx;
	height: 100%;
	font-size: 58rpx;
	font-family: Roboto;
	font-weight: bold;
	color: #333333;
}

.phonePlaceSytle {
	font-size: 32rpx;
	font-family: Source Han Sans CN;
	font-weight: normal;
	color: #666666;
}
/* 哩哩啦啦哩哩啦 */
.payTypeView {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.payType_title {
	margin: 60rpx auto auto 67rpx;
	align-self: flex-start;
	font-size: 38rpx;
	font-family: Source Han Sans CN;
	font-weight: bold;
	color: #000000;
}
.payTypeItem {
	margin-top: 57rpx;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.ItemL {
	margin-left: 73rpx;
	display: flex;
	align-items: center;
}
.ItemL text {
	margin-left: 23rpx;
	font-size: 38arpx;
	font-family: Source Han Sans SC;
	font-weight: normal;
}
.payView {
	width: 700rpx;
	height: 101rpx;
	margin-top: 112rpx;
	margin-bottom: 100rpx;
	position: relative;
}
.payNow {
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	position: absolute;
}
.tips {
	position: absolute;
	top: -26rpx;
	right: 47rpx;
	width: 174rpx;
	height: 47rpx;
}
</style>
